package com.freesky.mobile.user.controller;

import com.alibaba.fastjson2.JSON;
import com.freesky.biz.activity.service.ISmsCodeService;
import com.freesky.common.config.Constant;
import com.freesky.common.core.controller.BaseController;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.domain.entity.SysUser;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.common.utils.StringUtils;
import com.freesky.framework.web.service.SysLoginService;
import com.freesky.framework.web.service.SysPermissionService;
import com.freesky.system.mapper.SysUserMapper;
import com.freesky.system.service.ISysUserService;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.Set;

@RestController
@RequestMapping("/mobile/user")
public class MobileUserController extends BaseController {

    @Autowired
    @Qualifier("wxMpService")
    private WxMpService wxMpService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISmsCodeService smsCodeService;

    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysPermissionService permissionService;

    //获取验证码接口
    @RequestMapping("/getSmsCode")
    public AjaxResult getSmsCode(@NotNull String mobile,
                                 @RequestParam(required = false) String uuid,
                                  HttpServletRequest request,
                                  HttpServletResponse response){
        int retCode = 0;
        try {
            if(StringUtils.isEmpty(mobile)){
                return AjaxResult.error("操作失败，参数错误！");
            }

            SysUser sysUser = userMapper.checkPhoneUnique(mobile);
            if(sysUser == null){
                return AjaxResult.error("操作失败，系统异常");
            }

            String origin = "数字营销";
            smsCodeService.sendSmsCode(mobile,
                    Constant.SMS_TEMPLATE_LOGIN,
                    uuid,
                    origin);

            logger.info("【openId:"+uuid+"】【mobile:"+mobile+"】发送短信验证码");
            if(retCode>=0){
                return AjaxResult.success("验证码已发送");
            } else {
                return AjaxResult.error("操作失败，系统异常");
            }
        }
        catch(Exception e) {
            e.printStackTrace();
            return AjaxResult.error("操作失败，系统异常");
        }
    }


    //根据code获取openId
    @RequestMapping("/getTokenByCode")
    public AjaxResult getTokenByCode(@RequestParam(required = false) String appId,
                                     @RequestParam String code,
                                     @RequestParam(required = false) String scope,
                                     HttpServletRequest request, HttpServletResponse response) {
        try {
            if(StringUtils.isEmpty(appId)){
                appId = Constant.APP_ID;
            }

            if(StringUtils.isEmpty(scope)
                    || StringUtils.isEmpty(appId)){
                return AjaxResult.error("操作失败，参数不能为空!");
            }

            if (!this.wxMpService.switchover(appId)) {
                throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
            }

            logger.info("getTokenByCode 【appId:"+appId+"】【scope:"+scope+"】【code："+code);
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            logger.info("accessToken:"+ JSON.toJSONString(accessToken));

            String openId = accessToken.getOpenId();
            WxOAuth2UserInfo user = null;
            if("snsapi_userinfo".equalsIgnoreCase(scope)) {
                user = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
                logger.info("getTokenByWechatCode code：" + code + "获取用户：" + JSON.toJSONString(user));
            }
            //String openId = "oi6Ktjm7Z2A61WrwWaHw5mgJM7h4";
            return loginService.loginByOpenId(openId);

        } catch(Exception e) {
            logger.error("getTokenByCode:"+e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("操作失败，系统异常!");
        }
    }

    //根据code获取openId
    @RequestMapping("/loginByMobile")
    public AjaxResult loginByMobile(@RequestParam String mobile,
                                    @RequestParam String code,
                                    @RequestParam String uuid,
                                    HttpServletRequest request,
                                    HttpServletResponse response) {
        try {
            if(!smsCodeService.checkValidCode(mobile,code)){
                return AjaxResult.error("验证码不正确，请输入正确验证码!");
            }
            return loginService.loginByMobile(mobile,uuid);
        } catch(Exception e) {
            logger.error("getTokenByCode:"+e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("操作失败，系统异常!");
        }
    }

    @GetMapping("/logout")
    public AjaxResult logout(HttpServletRequest request,
                                    HttpServletResponse response) {
        try {
            Long userId = SecurityUtils.getUserId();
            sysUserService.updateUserOpenIdById("",String.valueOf(userId));
        } catch(Exception e) {
            logger.error("getTokenByCode:"+e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("操作失败,系统异常!");
        }
        return AjaxResult.success();
    }

    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }


}
